<template>
  <div>
    <el-form label-width="100" style="max-width: 450px" label-position="left">
      <el-form-item label="用户头像:">
        <el-upload
          class="avatar-uploader"
          :action="`${action}/user/uploadAvatar`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="userInfo.image_url" :src="userInfo.image_url" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户账号:">
        <el-col :span="18">
          <el-input :disabled="true" v-model="userInfo.account"></el-input
        ></el-col>
      </el-form-item>
      <el-form-item label="用户密码:">
        <el-button type="primary" size="default" @click="Dialog = true">修改密码</el-button>
      </el-form-item>
      <el-form-item label="用户姓名:">
        <el-col :span="18"> <el-input v-model="userInfo.name"></el-input></el-col>
        <el-col :span="3"></el-col>
        <el-col :span="3"
          ><el-button type="primary" size="default" @click="updateName">保存</el-button></el-col
        >
      </el-form-item>
      <el-form-item label="用户性别:">
        <el-col :span="18"> <el-input v-model="userInfo.sex"></el-input></el-col>
        <el-col :span="3"></el-col>
        <el-col :span="3"
          ><el-button type="primary" size="default" @click="updateSex">保存</el-button></el-col
        >
      </el-form-item>
      <el-form-item label="用户身份:">
        <el-col :span="18">
          <el-input v-model="userInfo.identity" :disabled="true"></el-input
        ></el-col>
      </el-form-item>
      <el-form-item label="用户部门:">
        <el-col :span="18">
          <el-input
            v-model="userInfo.department"
            :disabled="true"
            placeholder="请联系管理员修改"
          ></el-input
        ></el-col>
      </el-form-item>
      <el-form-item label="用户邮箱:">
        <el-col :span="18"> <el-input v-model="userInfo.email"></el-input></el-col>
        <el-col :span="3"></el-col>
        <el-col :span="3"
          ><el-button type="primary" size="default" @click="updateEmail">保存</el-button></el-col
        >
      </el-form-item>
    </el-form>
    <el-dialog @close="close" width="30%" title="修改密码" v-model="Dialog">
      <el-form :rules="rules" :model="passwordForm" ref="passwordFormRef">
        <el-form-item prop="oldPassword" label="旧密码">
          <el-input type="password" v-model="passwordForm.oldPassword"></el-input>
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码">
          <el-input type="password" v-model="passwordForm.newPassword"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="Dialog = false">取消</el-button>
        <el-button type="primary" size="default" @click="updatePassword">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormRules, UploadProps } from 'element-plus'
import {
  bindAccountAPI,
  updateEmailAPI,
  updateNameAPI,
  updatePasswordAPI,
  updateSexAPI
} from '@/api/user'
import { useRouter } from 'vue-router'
import { tracking } from '@/utils/operation'
// 导入路由
const router = useRouter()
// 获取项目地址
const action = import.meta.env.VITE_APP_BASE_API
// 导入仓库
const userStore = useUserStore()
// 存储用户信息
const userInfo = reactive<SettingUserInfo>({
  id: 0,
  image_url: '',
  account: null,
  password: '',
  sex: '',
  department: '',
  name: '',
  email: '',
  identity: ''
})
Object.assign(userInfo, userStore.UserInfo)

// 上传头像

// 头像上传成功回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.status === 1) {
    userStore.$patch({
      UserInfo: {
        image_url: response.url
      }
    })
    userInfo.image_url = response.url
    bindAccountAPI(userInfo.account!, response.onlyId, response.url)
    ElMessage({ type: 'success', message: '更新成功' })
  }
}

// 修改姓名
const updateName = async () => {
  const res = await updateNameAPI(userInfo.id as number, userInfo.name as string)
  if (res.status === 1) {
    userStore.$patch({
      UserInfo: {
        name: userInfo.name
      }
    })
    ElMessage({ type: 'success', message: '修改成功' })
  }
}
// 修改性别
const updateSex = async () => {
  const res = await updateSexAPI(userInfo.id as number, userInfo.sex as string)
  if (res.status === 1) {
    userStore.$patch({
      UserInfo: {
        sex: userInfo.sex
      }
    })
    ElMessage({ type: 'success', message: '修改成功' })
  }
}
// 修改邮箱
const updateEmail = async () => {
  const res = await updateEmailAPI(userInfo.id as number, userInfo.email as string)
  if (res.status === 1) {
    userStore.$patch({
      UserInfo: {
        email: userInfo.email
      }
    })
    ElMessage({ type: 'success', message: '修改成功' })
    tracking('', userInfo?.name!, '自己', '初级', `修改邮箱`)
  }
}

// 修改密码

// 获取表单实例
const passwordFormRef = ref()
// 修改密码弹窗
const Dialog = ref<boolean>(false)
// 修改密码弹窗关闭
const close = () => {
  passwordFormRef.value?.resetFields()
}
// 修改密码表单数据
const passwordForm = reactive<UpdatePassword>({
  oldPassword: '',
  newPassword: '',
  id: 0
})
// 表单校验规则
const rules = reactive<FormRules<UpdatePassword>>({
  oldPassword: { required: true, message: '请输入您的旧密码', trigger: 'blur' },
  newPassword: { required: true, message: '请输入您的新密码', trigger: 'blur' }
})

// 修改密码回调
const updatePassword = async () => {
  await passwordFormRef.value.validate()
  const res = await updatePasswordAPI(
    userInfo.id as number,
    passwordForm.newPassword,
    passwordForm.oldPassword
  )
  if (res.status === 1) {
    ElMessage({ type: 'success', message: '修改成功' })
    tracking('', userInfo?.name!, '自己', '初级', `修改密码`)
    router.push('/login')
  }
}
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 168px;
  height: 168px;
  display: block;
}
</style>
